package com.leetcode.June;

import java.util.Arrays;

/**
 * @Description: 轮转数组
 * @Author: Mr.Fxy
 * @CreateTime: 2024-07-21 09:05
 */
//例如[1,2,3,4,5], k = 3, 先反转整个数组得[5,4,3,2,1],再反转前k个得[3,4,5,2,1],再反转后n-k个得[3,4,5,1,2]即为答案

/**
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 */
public class RotatingArray {
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

    private static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}
